### Deployment K8s（CentOS7）
#0. 关闭swap
#（1）临时关闭swap分区, 重启失效;
swapoff -a
#（2）永久关闭swap分区
sed -ri 's/.*swap.*/#&/' /etc/fstab

#1.设置主机名
echo "设置主机名" 
hostnamectl set-hostname k8s-master
hostnamectl set-hostname k8s-node01

#2.设置IP虚拟服务器(IP Virtual Server)
echo " Open ipvs"
modprobe br_netfilter #向内核加载模块 modprobe -r br_netfilter 移除模块，
cat > /etc/sysconfig/modules/ipvs.modules <<EOF
#!/bin/bash
modprobe -- ip_vs
modprobe -- ip_vs_rr
modprobe -- ip_vs_wrr
modprobe -- ip_vs_sh
modprobe -- nf_conntrack
EOF
chmod 755 /etc/sysconfig/modules/ipvs.modules && bash /etc/sysconfig/modules/ipvs.modules &&
lsmod | grep -e ip_vs -e nf_conntrack
#use 'nf_conntrack' instead of 'nf_conntrack_ipv4' for linux kernel >= 4.19

#3.安装docker
echo "安装docker"    
yum install -y yum-utils device-mapper-persistent-data lvm2
#add aliyun docker repo
yum-config-manager \
--add-repo \
http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

#install docker
yum update -y && yum install -y docker-ce

# config daemon.
mkdir /etc/docker
cat > /etc/docker/daemon.json <<EOF
{
"registry-mirrors": [ "https://n1s5gkfw.mirror.aliyuncs.com"],
"insecure-registries": ["192.168.1.223:5000"],
"exec-opts": ["native.cgroupdriver=systemd"],
"log-driver": "json-file",
"log-opts": {
"max-size": "100m"
}
}

EOF
mkdir -p /etc/systemd/system/docker.service.d
# restart docker
systemctl daemon-reload && systemctl restart docker && systemctl enable docker

#4.安装 kubeadm kubectl kubelet
echo "安装 kubeadm kubectl kubelet"
cat <<EOF > /etc/yum.repos.d/kubernetes.repo
[kubernetes]
name=Kubernetes
baseurl=http://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64
enabled=1
gpgcheck=0
repo_gpgcheck=0
gpgkey=http://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg
http://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key.gpg
EOF

yum -y install kubeadm kubectl kubelet
systemctl enable kubelet.service

#5.拉取镜像
echo "拉取镜像"
#!/bin/bash
#pull images

ver=v1.21.1 #设置拉取的版本
registry=registry.cn-hangzhou.aliyuncs.com/google_containers
images=`kubeadm config images list --kubernetes-version=$ver |awk -F '/' '{print $2}'`

for image in $images
do
if [ $image != coredns ];then
    docker pull ${registry}/$image
    if [ $? -eq 0 ];then
        docker tag ${registry}/$image k8s.gcr.io/$image
        docker rmi ${registry}/$image
    else
        echo "ERROR: 下载镜像报错，$image"
    fi
else
    docker pull coredns/coredns:1.8.0
    docker tag coredns/coredns:1.8.0  k8s.gcr.io/coredns/coredns:v1.8.0
    docker rmi coredns/coredns:1.8.0
fi
done
chmod +x pullimages.sh && ./pullimages.sh

#6.初始化master节点 kubeadm-config.yaml
kubeadm init --ignore-preflight-errors=NumCPU --upload-certs | tee kubeadm-init.log
# kubeadm init --kubernetes-version=v1.21.1 --pod-network-cidr=10.244.0.0/16 --apiserver-advertise-address=192.168.1.223


#7.安装网络插件 
echo "安装网络插件flannel"
kubectl apply -f kube-flannel.yml
